package com.heaven.schedule;

import com.heaven.constant.VideoConstants;
import com.heaven.customerServer.customerController.cacheEntity.PlayTimeCache;
import com.heaven.service.VideoService;
import com.heaven.utils.DateUtils;
import com.heaven.utils.RedisUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class VideoSchedule {
    @Resource
    private ScheduledExecutorService scheduledExecutorService;
    @Resource
    private VideoService videoService;
    @Resource
    private RedisUtils redisUtils;

    /**
     * 清除多余的播放token
     * 每隔一天执行一次
     */
    @Scheduled(fixedRate = 1, timeUnit = TimeUnit.DAYS)
    private void clearPlayToken(){
        CompletableFuture.runAsync(() -> {
            List<String> keys = redisUtils.keys(VideoConstants.PLAY_COUNT_TOKEN_KEY_PREFIX+"*").stream().toList();
            for (String key : keys) {
                PlayTimeCache playTimeCache = redisUtils.getCacheObject(key);
                if(DateUtils.differentDaysByMillisecond(new Date(), playTimeCache.getCreateTime()) > 1){
                    redisUtils.deleteObject(key);
                }
            }
        }, scheduledExecutorService);
    }

    /**
     * 每5min，检查视频是否在minio中
     */
    @Scheduled(fixedRate = 5, timeUnit = TimeUnit.MINUTES)
    private void checkVideoIsInMinio(){
        CompletableFuture.runAsync(() -> {
            log.info("check video is inMinio...");
            // 搜索所有文件不在minio中的视频条目
            Query query = Query.query(Criteria.where("is_in_minio").is(0));
            videoService.selectList(query).forEach((entity) -> {
                String videoObjectName = entity.getUrl().split(":")[1];
                if(videoService.isVideoExistInMinio(videoObjectName)){
                    // 更新数据库中视频条目的minio状态
                    videoService.updateOne(Query.query(Criteria
                            .where("_id").is(entity.getVideoId())), Update.update("is_in_minio", 1));
                }
            });
        }, scheduledExecutorService);
    }
}
